//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 周小伟 on 16/8/23.
//  Copyright © 2016年 周小伟. All rights reserved.
// 授权token https://api.weibo.com/oauth2/access_token
/**
 必选	      类型及范围	    说明
 client_id	    true	   string	申请应用时分配的AppKey。
 client_secret	true	   string	申请应用时分配的AppSecret。
 grant_type	    true	   string	请求的类型，填写authorization_code
 
 grant_type为authorization_code时
 必选	      类型及范围	 说明
 code	        true	string	调用authorize获得的code值。
 redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
 */


//App Key：
//1316547219
//
//App Secret：
//cdac6a8920ab49f667c2d75293e39ba1

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    let webView = UIWebView()
    
    @objc private func closed(){
        self.dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    @objc private func fullAccount(){
        let jsString = "document.getElementById('userId').value = '420821129@qq.com',document.getElementById('passwd').value = 'Liudan89512';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
        self.loadOauthPage()
        // Do any additional setup after loading the view.
    }
    

    private func loadOauthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(OAuthViewController.closed))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(OAuthViewController.fullAccount))
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

}


extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //the bool meas that if it been seted true ,the system could work normally,or it maybe crashed!
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //网络请求页面
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        if !urlString.hasPrefix("http://www.baidu.com"){
            return false
        }
        
        guard let query = request.URL?.query else{
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        UserAccountViewModel().loadAccessToken(code) { (error) in
            print("come here")
            if error != nil{
                SVProgressHUD.showInfoWithStatus(AppErrorTip)
                return
            }
            
            self.dismissViewControllerAnimated(true, completion: { 
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewController, object: "Welcome")
            })
        }
        return false
    }
    func 截取字符串()->String{
        var urlString = "hello,world"
        let end = urlString.startIndex.advancedBy(27)
        let start = urlString.startIndex
        let range = start..<end
        urlString.removeRange(range)
        return urlString
    }
    
}

